/* global window */
import modelExtend from 'dva-model-extend'
import * as chatroomService from '../../services/chatroom'
import {pageModel} from 'utils/model'
import pathToRegexp from 'path-to-regexp'


const {queryChatroomChatRecords} = chatroomService

export default modelExtend(pageModel, {
  namespace: 'chatroomDetail',

  state: {
    disabled: true,
    data: {},
    chatRoomChatRecordsList: [],
    chatRoomChatRecordsListPagination: {},
  },

  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname}) => {
        const match = pathToRegexp('/chatroom/:id').exec(pathname)
        if (match) {
          dispatch({type: 'chatroomMember/query', payload: {chatroomId: match[1], current: 1, size: 10}})
        }
      })
    },
  },

  effects: {

    * queryChatroomChatRecords ({payload = {}}, {call, put}) {

      const response = yield call(queryChatroomChatRecords, payload)
      const {data} = response
      if (response) {
        yield put({
          type: 'updateState',
          payload: {
            chatRoomChatRecordsList: data,
            chatRoomChatRecordsListPagination: {
              current: Number(payload.current) || 1,
              pageSize: Number(payload.size) || 10,
              total: data.total || Number(payload.pageSize),
            },
          },
        })
      }
    },

  },


  reducers: {
    getDetail (state, {payload}) {
      return {...state, ...payload}
    },
  },
})
